package com.yifushidai.service.impl;

import com.github.pagehelper.PageHelper;
import com.yifushidai.entity.DynamicTempkey;
import com.yifushidai.mapper.DynamicTempkeyMapper;
import com.yifushidai.service.DynamicTempkeyService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import tk.mybatis.mapper.entity.Example;

import java.util.Date;
import java.util.List;

@Service
public class DynamicTempkeyServiceImpl extends BaseService<DynamicTempkey> implements DynamicTempkeyService {

    @Autowired
    private DynamicTempkeyMapper dynamicTempkeyMapper;

    @Override
    public List<DynamicTempkey> queryListByMac(String mac) {
        // 创建Example
        Example example = new Example(DynamicTempkey.class);
        example.setOrderByClause("expire_date ASC");

        // 创建Criteria 添加条件
        Example.Criteria criteria = example.and();
        criteria.andEqualTo("mac", mac);

        PageHelper.startPage(1, 10);
        return selectByExample(example);
    }

    @Override
    public int saveOrUpdate(DynamicTempkey record) {
        // 创建Example
        Example example = new Example(DynamicTempkey.class);
        // 创建Criteria 添加条件
        Example.Criteria criteria = example.createCriteria();
        criteria.andEqualTo("mac", record.getMac());
        criteria.andEqualTo("pushIndex", record.getPushIndex());

        List<DynamicTempkey> db = dynamicTempkeyMapper.selectByExample(example);

        if (db.isEmpty()) {//新建
            return saveNotNull(record);
        } else {//编辑
            return updateByExampleSelective(record, example);
        }
    }

    @Override
    public int deleteByMacAndPushIndex(DynamicTempkey record) {
        // 创建Example
        Example example = new Example(DynamicTempkey.class);

        // 创建Criteria 添加条件
        Example.Criteria criteria = example.createCriteria();
        criteria.andEqualTo("mac", record.getMac());
        criteria.andEqualTo("pushIndex", record.getPushIndex());

        return deleteByExample(example);
    }

    @Override
    public int deleteByMac(DynamicTempkey record) {
        // 创建Example
        Example example = new Example(DynamicTempkey.class);

        // 创建Criteria 添加条件
        Example.Criteria criteria = example.createCriteria();
        criteria.andEqualTo("mac", record.getMac());

        return deleteByExample(example);
    }

    @Override
    public int deleteByExpire() {
        // 创建Example
        Example example = new Example(DynamicTempkey.class);

        // 创建Criteria 添加条件
        Example.Criteria criteria = example.createCriteria();
        criteria.andLessThanOrEqualTo("expireDate", new Date());

        return deleteByExample(example);
    }

}